const router=require("express").Router();
const PW=require("png-word");
const pw=new PW();
const R=require("random-word");
const User=require("./Schema1");
const Message=require("./Schema2");


router.get("/",async function (req,res){
   let firstNum=Math.floor(Math.random()*10);
   let secondNum=Math.floor(Math.random()*10);
   res.locals.firstNum=req.session.firstNum=firstNum;
   res.locals.secondNum=req.session.secondNum=secondNum;
      var  user=req.session.user || "";
      var page=Number(req.query.page) || 1 ;
      var lastPage=page-1 > 0 ? page-1 : 1 ;
      var nextPage=page+1;
  var message=await Message.find().sort("-createTinme").limit(10).skip((page-1)*10);
          res.render("work",{user,message,nextPage,lastPage});
});
//注册，将注册信息保存在User中
router.post("/reg",async function (req,res){
  //用户填写了用户名，用户名此前没有人注册过，用户密码两次确认相同。用户验证码
      var userArry=await User.find({userName:req.body.loginName});
  if(req.body.loginName && userArry.length == 0 &&req.body.loginPassword === req.body.confirm){
    var loginName=req.body.loginName;//用户名
    var loginPassword=req.body.loginPassword;//密码
    const user=new User({
      userName:loginName,
      password:loginPassword
    });
    await user.save();
  }
  else{
    console.log("该用户名已被注册");
  }
  res.redirect("back");
});

//登录成功时，更新req.session对象
router.post("/login",async function (req,res){
       var name=req.body.loginName;//比如我注册的时候是555
       var password=req.body.loginPassword;//
       var Vcode=req.body.Vcode;
       if(await User.find({name}).where("password").eq(password) && req.session.firstNum+req.session.secondNum === Number(Vcode)){
              req.session.user=name;
              console.log("登录成功");
       }
       res.redirect("back");
});

router.get("/out",function (req,res){
      req.session.user=undefined;
      res.redirect("back");
});

//图形验证码


//发送消息，将消息添加进在message数组中
router.post("/sendMessage",async function (req,res){
 if(req.session.user){
  var message=req.body.message;
  var userName=req.session.user;
  var now=new Date();
  var message=new Message({
    message:message,
    userName:userName,
    createTime:now
  });
      await message.save();
      console.log("发送成功");
}
res.redirect("back");
});


module.exports=router;
